package com.laulkar.dataproviders;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.res.Resources;
import android.content.res.XmlResourceParser;

import com.laulkar.R;

public class DataProvider {

	public static MtaStatus parseStatus(Resources r)
	throws XmlPullParserException, IOException
	{
		MtaStatus status = new MtaStatus();

		//Resources r = getResources();
		XmlResourceParser xpp = r.getXml(R.xml.servicestatus);

		xpp.next();
		int eventType = xpp.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT)
		{
			if(eventType == XmlPullParser.START_TAG)
			{
				//stringBuffer.append("\nSTART_TAG: "+xpp.getName());
				String tag = xpp.getName();
				if(tag.equals("subway"))
				{
					ArrayList<Subway> subways = parseSubway(xpp);
					status.setSubways(subways);
					break;
				}
			}
			eventType = xpp.next();
		}

		return status;
	}

	/* This function parses the MTA status XML */
	public static ArrayList<Subway> parseSubway(XmlResourceParser xpp) throws XmlPullParserException, IOException
	{
		ArrayList<Subway> subways = new ArrayList<Subway>();
		xpp.next();
		int eventType = xpp.getEventType();
		Subway s = new Subway();
		while (eventType != XmlPullParser.END_DOCUMENT)
		{
			if(eventType == XmlPullParser.START_TAG)
			{
				//stringBuffer.append("\nSTART_TAG: "+xpp.getName());
				String tag = xpp.getName();
				if(tag.equals("line"))
				{
					s = new Subway();
				}
				if(tag.equals("name"))
				{
					s.setLine(xpp.nextText());
				}
				else if (tag.equals("status"))
				{
					s.setStatus(xpp.nextText());
				}
				else if (tag.equals("text"))
				{
					s.setText(xpp.nextText());
				}
			}
			else if(eventType == XmlPullParser.END_TAG)
			{
				if(xpp.getName().equals("line"))
					subways.add(s);
			}

			eventType = xpp.next();
		}
		//stringBuffer.append("\n--- End XML ---");
		return subways;
	}

	final static String STATUS_URL = "http://transitstatus.appspot.com/subway/status/";

	public static MtaStatus getStatusCSV()
	{
		MtaStatus status = new MtaStatus();
		ArrayList<Subway> subways = new ArrayList<Subway>();
		try {
			URL url = new URL(STATUS_URL);
			URLConnection yc = url.openConnection();
			BufferedReader in = new BufferedReader(
					new InputStreamReader(
							yc.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null)
			{
				String [] csvSplit = inputLine.split(",");
				Subway s = new Subway(csvSplit[0], csvSplit[1]);
				subways.add(s);
			}

			in.close();
			status.setSubways(subways);


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return status;
	}
}
